package com.houger.ddd.seckill.repository;

import com.houger.ddd.seckill.infra.entity.ActivityInstance;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;
import java.util.Optional;

/**
 * @author Houger.
 * @date 2024年05月20日 17:30.
 */
@Repository
public interface ActivityInstanceRepository extends JpaRepository<ActivityInstance,Long>, JpaSpecificationExecutor<ActivityInstance> {

   Optional<List<ActivityInstance>> findByTemplateIdAndInitiatorId(Long templateId, String userId);

    @Transactional(rollbackFor = Exception.class)
    @Modifying(clearAutomatically = true)
    @Query(value = "update activity_instance set instance_status = ?3 where id = ?1 and instance_status=?2",nativeQuery=true)
    int updateStatus(Long instanceId, int fromStatus, int toStatus);

    @Transactional(rollbackFor = Exception.class)
    @Modifying(clearAutomatically = true)
    @Query(value = "update activity_instance set instance_status = ?3 where id = ?1 and instance_status=?2 and version=?4",nativeQuery=true)
    int updateStatus(Long instanceId, int fromStatus, int toStatus,Long version);
}
